package com.example.config;

import com.example.entity.Emp;
import com.example.mapper.EmpMapper;
import com.example.utils.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 密码初始化器
 * 在应用启动时检查并初始化员工密码
 */
@Component
public class PasswordInitializer implements CommandLineRunner {

    @Autowired
    private EmpMapper empMapper;
    
    private final PasswordEncoder passwordEncoder = new PasswordEncoder();

    /**
     * 应用启动时执行
     */
    @Override
    @Transactional
    public void run(String... args) {
        // 查询所有员工
        List<Emp> empList = empMapper.list(null, null, null, null);
        
        // 检查并初始化密码
        for (Emp emp : empList) {
            // 如果密码为空或者不是加密格式，则设置默认密码
            if (emp.getPassword() == null || !emp.getPassword().startsWith("$2a$")) {
                emp.setPassword(passwordEncoder.encode("123456"));
                emp.setUpdateTime(java.time.LocalDateTime.now());
                empMapper.update(emp);
            }
        }
    }
} 